<?php

namespace app\common\model;

use app\common\model\Base;
use Exception;
use think\Db;
use app\common\model\ProductStorageOrder;

class ProductPurchaseOrder extends Base {

    public function getStatusTextAttr($value, $data) {
        $status = [-1 => '<span class="label label-warning">部分入库</span>', -2 => '<span class="label label-success">已完成</span>', 0 => '待入库'];
        return $status[$data['status']];
    }

    /**
     * 一订单对应多个订单数据
     * @return type
     */
    public function orderData() {
        return $this->hasMany('ProductPurchaseOrderData', 'order_id');
    }

    public function add_submit($post, $products) {
        // 启动事务
        Db::startTrans();
        try {
            //很长很长 $amount
            $data['order_number'] = date('YmdtHis') . rand(100, 999) . UID;
            $data['member_id'] = UID;
            $data['total_quantity'] = $post['total_quantity'];
            $data['total_price'] = $post['total_price'];
            $data['remark'] = $post['remark'];
            $data['create_time'] = time();

            $insert_id = Db::name('product_purchase_order')->insertGetId($data);


            if ($insert_id) {
                foreach ($products as $product) {
                    $order_data['order_id'] = $insert_id;
                    $order_data['product_id'] = $product['id']; // 产品ID
                    $order_data['supplier_id'] = $product['supplier_id'];
                    $order_data['quantity'] = $product['quantity'];
                    $order_data['group_price'] = $product['group_price'];
                    $order_data['amount'] = $product['group_price'] * $product['quantity'];

                    // 产品快照
                    $product_snapshot = Db::name('product')
                            ->alias('p')
                            ->join('product_category pc', 'pc.id=p.c_id', 'LEFT')
                            ->where('p.id', $product['id'])
                            ->field('p.*,pc.name as category')
                            ->find();
                    $product_snapshot['product_type'] = Db::name('product_type')->where('id', $product_snapshot['type'])->value('title');
                    $order_data['product_snapshot'] = serialize($product_snapshot);

                    Db::name('product_purchase_order_data')->insert($order_data);
                }
            } else {
                throw new \Exception('入库单生成失败');
            }
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->setError($e->getMessage());
        }
    }

    public function model_where() {

        if (request()->get('timea'))
            $this->where('a.create_time', '>=', strtotime(request()->get('timea') . ' 00:00:00'));
        if (request()->get('timeb'))
            $this->where('a.create_time', '<=', strtotime(request()->get('timeb') . ' 23:59:59'));
        if (request()->get('keyword'))
            $this->where('p.name|p.code', 'like', '%' . request()->get('keyword') . '%');

        // $this->where('a.u_id', UID);
        //     $this->join('product p', 'p.id=a.prodcut_id');
        $this->join('system_user su', 'su.id=a.member_id');

        $this->field('a.*,su.nickname as staff_nickname');

        $this->with('order_data');

        $this->order('a.id desc');
        $this->alias('a');
        return $this;
    }

    public function query_delete($id) {

        Db::startTrans();
        try {


            // 同步删除所有的入库记录
            // 先查询所有的入库记录
            $storage_ids = Db::name('rel_purchase_storage')
                    ->where('purchase_order_data_id', 'IN', function($query) use ($id) {
                        $query->name('product_purchase_order_data')->where('order_id', $id)->field('id');
                    })
                    ->column('storage_id');
                    
             

            // 循环删除所有入库记录
            foreach ($storage_ids as $storage_id) {
                $productStorageOrderModel = new ProductStorageOrder();
                $productStorageOrderModel->storage_undo($storage_id);
                if ($productStorageOrderModel->hasError()) {
                    throw new \Exception($productStorageOrderModel->getError());
                }
            }



            //删除w_order_data的所有数据
            Db::name('product_purchase_order_data')->where('order_id', '=', $id)->delete();
            //删除w_order下面的数据，单条
            Db::name('product_purchase_order')->where('id', '=', $id)->delete();


            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->setError($e->getMessage());
        }
    }

    /**
     * @title 数量
     * @param type $listss
     * @param type $datea
     * @param type $dateb
     * @return type
     */
    private function get_count($listss, $datea, $dateb) {
        $vars = 0;
        foreach ($listss as $var) {
            $create_time = strtotime($var['create_time']);
            if ($create_time >= $datea && $create_time <= $dateb)
                $vars += $var['quantity'];
        }
        return $vars;
    }

    /**
     * @title 销售价格
     * @param type $listss
     * @param type $datea
     * @param type $dateb
     * @return type
     */
    private function get_sales($listss, $datea, $dateb) {
        $vars = 0;
        foreach ($listss as $var) {
            $create_time = strtotime($var['create_time']);
            if ($create_time >= $datea && $create_time <= $dateb) {
                $vars += $var['amount'];
            }
        }
        return $vars;
    }

    /**
     * @title 实际收入(因为有退货)
     * @param type $listss
     * @param type $datea
     * @param type $dateb
     * @return type
     */
    private function get_actual($listss, $datea, $dateb) {
        $vars = 0;
        foreach ($listss as $var) {
            $create_time = strtotime($var['create_time']);
            if ($var['returns'] == 0 && $create_time >= $datea && $create_time <= $dateb)
                $vars += $var['amount'];
        }
        return $vars;
    }

    /**
     * @title 报表
     * @param type $day
     * @return type
     */
    public function chart($day) {

        $lists = $this->field('psod.*,a.create_time')->group('psod.id')->select();


        //销售 sales 
        //实际 actual
        //利润 profit

        $result = [];
        for ($index = 0; $index < $day; $index++) {

            $date = date('Y-m-d', strtotime($_GET['timea']) + ($index * 86400));
            $datea = strtotime($date . ' 00:00:00');
            $dateb = strtotime($date . ' 23:59:59');

            $result['sales'][$index + 1] = $this->get_sales($lists, $datea, $dateb);
            $result['actual'][$index + 1] = $this->get_actual($lists, $datea, $dateb);
            //  $result['profit'][$index + 1] = $this->get_profit($lists, $datea, $dateb);
            $result['quantity'][$index + 1] = $this->get_count($lists, $datea, $dateb);

            $date_short = date('d', strtotime($date));

            $result['date'][$index + 1] = "'{$date_short}'";
        }

        return $result;
    }

}
